﻿using UtilPublic.ServerLoger;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace UtilPublic.Http
{
    /// <summary>
    /// 
    /// </summary>
    public class MyHttpServer : HttpServer
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="port">端口</param>
        /// <param name="funchandle">处理方法</param>
        public MyHttpServer(int port, Func<int, string, (bool, string)> funchandle)
            : base(port)
        {
            FuncHandle = funchandle;
        }
        private Func<int, string, (bool, string)> FuncHandle = new Func<int, string, (bool, string)>(FuncHandleDefault);
        private static (bool, string) FuncHandleDefault(int port, string content)
        {
            bool result1 = false;
            string result2 = "";
            return (result1, result2);
        }
        /// <summary>
        /// GET
        /// </summary>
        /// <param name="p"></param>
        public override void handleGETRequest(HttpProcessor p)
        {
            string data = p.http_url;
            int pos = data.IndexOf("?");
            if (pos < 0)
            {
                p.outputStream.Write("run health!!");
                loger.Debug($"GET request error:{p.http_url}");
                return;
            }

            string content = data.Substring(pos + 1);

            var (CheckResult, contentrsp) = FuncHandle(port, content);

            if (!string.IsNullOrEmpty(contentrsp))
            {
                p.WriteSuccess(contentrsp);
            }
            if (!CheckResult)
            {
                loger.Fatal($"handleGETRequest Fail {contentrsp} {content}");
            }
        }
        /// <summary>
        /// POST
        /// </summary>
        /// <param name="p"></param>
        /// <param name="inputData"></param>
        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            loger.Debug($"POST request: {p.http_url}");
            string content = inputData.ReadToEnd();
            loger.Debug($"POST data: {content}");

            var (CheckResult, contentrsp) = FuncHandle(port, content);

            if (!string.IsNullOrEmpty(contentrsp))
            {
                p.WriteSuccess(contentrsp);
            }
            if (!CheckResult)
            {
                loger.Fatal($"handlePOSTRequest Fail {contentrsp} {content}");
            }
        }
    }
}
